package com.face.gaoml.netlibrary.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 时间相关操作
 * @author 张艳军
 * @version 创建时间：2011-8-3 下午05:23:41
 */
public class DateUtil 
{
	private static long l_timeBwt = 0;
	/*
	 * 根据服务端和客户端时间差估算出服务器当前时间
	 */
	public static String getNow(String pattern){
		Calendar now = Calendar.getInstance();
		now.add(Calendar.MILLISECOND, (int) l_timeBwt);
		SimpleDateFormat df = new SimpleDateFormat(pattern);
		return (String)df.format(now.getTimeInMillis());
	}

	/**
	 * 取得当前时间,以时间格式返回
	 * @return
	 */
	public static String getDateTimeNow(){
		return getNow("yyyy-MM-dd HH:mm:ss");
	}
	
	/**
	 * 取得当前时间,以时间格式返回
	 * @return
	 */
	public static String getDateTimeNow2(){
		return getNow("yyyy年MM月dd日");
	}
	/**
	 * 取得当前时间,以串格式返回
	 * @return
	 */
	public static String getStringNow(){
		return getNow("yyyyMMddHHmmss");
	}
	
	/**
	 * 取时间 差
	 * @param begintimestr
	 * @param endtimestring
	 * @return
	 */
	public static long Comparison(String begintimestr, String endtimestring , String format){
		  if(begintimestr == null || endtimestring == null){
			  return 0;
		  } 
		  long out =0;
		  try {
			  SimpleDateFormat df = new SimpleDateFormat(format);
			  Date now = df.parse(endtimestring);

		   Date date=df.parse(begintimestr);

		   out=now.getTime()-date.getTime();

		} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		}
		return out;
	}
	public static String Date2String(Date now, String format){
		 if(format ==null){
			 format ="yyyy-MM-dd HH:mm:ss";
		 }
		java.text.DateFormat format1 = new SimpleDateFormat(format);
		String datestring = format1.format(now);
		return datestring;
	}

	public static String transferLongToDate(Long millSec){

	     SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

	     Date date= new Date(millSec);

	            return sdf.format(date);

	    }

	public static Date string2Date(String datestring, String format)
	{
		if(format==null)
		{
			format = "yyyy-MM-dd HH:mm:ss";
		}
		Date now = null;
		try {
			  SimpleDateFormat df = new SimpleDateFormat(format);
			  now = df.parse(datestring);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return now;
	}
	public static String string2DateString(String datestring, String sourceFormat, String targetFormat)
	{
		if(sourceFormat == null)
		{
			sourceFormat = "yyyy-MM-dd HH:mm:ss";
		}
		Date now = null;
		String dateString = null;
		try
		{
			SimpleDateFormat df = new SimpleDateFormat(sourceFormat);
			now = df.parse(datestring);

			java.text.DateFormat format1 = new SimpleDateFormat(targetFormat);
			dateString = format1.format(now);
		}
		catch (ParseException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dateString;
	}
	/**
	 * 将yyyy-MM-dd 转为 年 月 日
	 * @param dateString
	 * @return
	 */
	public static String string2DateStringForChinese(String dateString)
	{
		String[] splitStringArray = dateString.split("-", 3);
		StringBuffer stringBuffer = new StringBuffer();
		int length = splitStringArray.length;
		if(length == 3)
		{
			stringBuffer.append(splitStringArray[0]+"年");
			stringBuffer.append(splitStringArray[1]+"月");
			stringBuffer.append(splitStringArray[2]+"日");
		}
		else if(length == 2)
		{
			stringBuffer.append(splitStringArray[0]+"月");
			stringBuffer.append(splitStringArray[1]+"日");
		}

		return stringBuffer.toString();
	}


	public static String string2DateStringForChinese(String datestring, String sourceFormat, String targetFormat)
	{
		String dateString = string2DateString(datestring,sourceFormat,targetFormat);
	//	LogUtil.e("test","dateString="+dateString);
		String[] splitStringArray = dateString.split("-", 3);
		StringBuffer stringBuffer = new StringBuffer();
		int length = splitStringArray.length;
		if(length == 3)
		{
			stringBuffer.append(splitStringArray[0]+"年");
			stringBuffer.append(splitStringArray[1]+"月");
			stringBuffer.append(splitStringArray[2]+"日");
		}
		else if(length == 2)
		{
			stringBuffer.append(splitStringArray[0]+"月");
			stringBuffer.append(splitStringArray[1]+"日");
		}

		return stringBuffer.toString();
	}
	/**
     * 获取两个时间格式的字符之间的 时间差
     * @param serverCacheUpdateTimeString 服务端缓存时间
     * @param localCacheupdateTimeString  本地缓存时间
     * @return
     */
	public static long getDifferenceBetweenDate(String serverCacheUpdateTimeString, String localCacheupdateTimeString)
    {
        long differenceDount = 0;
        long serverCacheUpdateTimeCount = 0;
        long localCacheupdateTimeCount = 0;
        try
        {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(serverCacheUpdateTimeString.length() != 0)
            {
                Date serverCacheUpdateTime  = df.parse(serverCacheUpdateTimeString);
                serverCacheUpdateTimeCount = serverCacheUpdateTime.getTime();
            }
            if(localCacheupdateTimeString.length() != 0)
            {
                Date localCacheupdateTime  = df.parse(localCacheupdateTimeString);
                localCacheupdateTimeCount = localCacheupdateTime.getTime();
            }
            differenceDount = localCacheupdateTimeCount - serverCacheUpdateTimeCount;
        }
        catch (ParseException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return differenceDount;
    }
	/**
	 * 获取俩个时间 格式的字符之间的 时间间隔
	 * @param begintimestr 开始时间
	 * @param endtimestring 结束时间
	 * @return
	 * @throws ParseException
	 */
	public static String getBetween(String begintimestr, String endtimestring)
	{
		String out="";

		if(begintimestr == null || endtimestring == null)
		{
			return "";
		}
		try
		{
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date begin_time = df.parse(begintimestr);
			Date end_time = df.parse(endtimestring);
			Date now_time =  new Date();
			//计算时差
			if (l_timeBwt == 0) 
			{
				l_timeBwt = begin_time.getTime() - now_time.getTime() ;
			} 
			long millisecond = end_time.getTime() - now_time.getTime() - l_timeBwt;
			if(millisecond < 0)
			{
				out = "0";
				return out;
			}
			
//			long day = millisecond/(24*60*60*1000);
//			long hour = (millisecond/(60*60*1000)-day*24);
//			long min = ((millisecond/(60*1000))-day*24*60-hour*60);
//			long s = (millisecond/1000-day*24*60*60-hour*60*60-min*60);
//			out = day+"天"+hour+"小时"+min+"分"+s+"秒";
		
            long hour = millisecond/(60*60*1000);
            long min = ((millisecond/(60*1000)) - hour*60);
            long s = (millisecond/1000 - hour*60*60-min*60);
            out = hour+"-"+min+"-"+s;
		} 
		catch (ParseException e)
		{
				// TODO Auto-generated catch block
				e.printStackTrace();
		}
		 return out;
	}
	/**
	* 获取两个日期之间的间隔天数
	* @return
	*/
	public static int getIntervalDays(Date startDate, Date endDate)
	{
	        Calendar fromCalendar = Calendar.getInstance();
	        fromCalendar.setTime(startDate);  
	        fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
	        fromCalendar.set(Calendar.MINUTE, 0);
	        fromCalendar.set(Calendar.SECOND, 0);
	        fromCalendar.set(Calendar.MILLISECOND, 0);
	  
	        Calendar toCalendar = Calendar.getInstance();
	        toCalendar.setTime(endDate);  
	        toCalendar.set(Calendar.HOUR_OF_DAY, 0);
	        toCalendar.set(Calendar.MINUTE, 0);
	        toCalendar.set(Calendar.SECOND, 0);
	        toCalendar.set(Calendar.MILLISECOND, 0);
	  
	        return (int) ((toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24));
	}
	/**
	 * 获取两个日期之间时间间隔
	 * end -start
	 * @return
	 */
	public static long getIntervalDayMillins(Date startDate, Date endDate)
	{
		Calendar fromCalendar = Calendar.getInstance();
		fromCalendar.setTime(startDate);  
		fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
		fromCalendar.set(Calendar.MINUTE, 0);
		fromCalendar.set(Calendar.SECOND, 0);
		fromCalendar.set(Calendar.MILLISECOND, 0);
		
		Calendar toCalendar = Calendar.getInstance();
		toCalendar.setTime(endDate);  
		toCalendar.set(Calendar.HOUR_OF_DAY, 0);
		toCalendar.set(Calendar.MINUTE, 0);
		toCalendar.set(Calendar.SECOND, 0);
		toCalendar.set(Calendar.MILLISECOND, 0);
		
		return (long) ((toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) );
	}
	/**
	 *  获取俩个时间 的间隔
	 * @param begintimestr
	 * @param endtimestring
	 * @return
	 * @throws ParseException
	 */
	public static String getBetween(Date begintimestr, Date endtimestring) throws ParseException
	{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date now =endtimestring;
		Date date=begintimestr;
		long l=now.getTime()-date.getTime();
		long day=l/(24*60*60*1000);
		long hour=(l/(60*60*1000)-day*24);
		long min=((l/(60*1000))-day*24*60-hour*60);
		long s=(l/1000-day*24*60*60-hour*60*60-min*60);
		String out = day+"天"+hour+"小时"+min+"分"+s+"秒";
		return out;
	}
	/**
	 * 时间格式字符串转换成时间 对象
	 * @param timeString
	 * @return
	 * @throws ParseException
	 */
	public static Date getDateByTimeString(String timeString, String format) throws ParseException
	{
		if(format==null)
		{
			format="yyyy-MM-dd HH:mm:ss";
		}
		SimpleDateFormat df = new SimpleDateFormat(format);
		Date date;

		date = df.parse(timeString);
		return date;

	}
	/**
	 * 获取 减去 向应 数量(日,小时,分,妙)后 的时间
	 * @param now
	 * @param subtime
	 * @param format
	 * @return
	 */
	public static Date getSubtdate(Date now, int subtime, String format){
		if(format == null){
			format = "ss";
		}
		long longsubtime = 0 ;
		if("ss".equals(format)){
			longsubtime = subtime*1000;
		}
		if("mm".equals(format)){
			longsubtime = subtime*1000*60;
		}
		if("HH".equals(format)){
			longsubtime = subtime*1000*60*60;
		}
		if("dd".equals(format)){
			longsubtime = subtime*1000*60*60*24;
		}
		
		return new Date(now.getTime()-longsubtime);
	}
	
	/**
     * 获得指定日期的前一天
     * 
     * @param specifiedDay
     * @return
     * @throws Exception
     */
    public static String getSpecifiedDayBefore(String specifiedDay) {
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day - 1);

        String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c
                .getTime());
        return dayBefore;
    }

    /**
     * 获得指定日期的后一天
     * 
     * @param specifiedDay
     * @return
     */
    public static String getSpecifiedDayAfter(String specifiedDay) {
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day + 1);

        String dayAfter = new SimpleDateFormat("yyyy-MM-dd")
                .format(c.getTime());
        return dayAfter;
    }
	public static void main(String[] args)
	{
//		String time = getBetween("2011-08-23 11:23:40","2011-08-23 14:00:00");
	}
	
	//获取指定时间星期几
	public static String getWeek(String date, String formart){
		String week = "";
		Calendar c = Calendar.getInstance();
		Date mDate = string2Date(date, formart);
		c.setTime(mDate);
		week = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
		
		if("1".equals(week)){  
            week ="周日";  
        }else if("2".equals(week)){  
            week ="周一";  
        }else if("3".equals(week)){  
            week ="周二";  
        }else if("4".equals(week)){  
            week ="周三";  
        }else if("5".equals(week)){  
            week ="周四";  
        }else if("6".equals(week)){  
            week ="周五";  
        }else if("7".equals(week)){  
            week ="周六";  
        }
		
		return week;
	}
	
	/**
	 * 将yyyy-MM-dd HH:mm 转成 x年x月x日 HH:mm
	 * @param time
	 * @return
	 */
	public static String getDateStringMIX(String time){
		
		String ymd = DateUtil.string2DateString(time, "yyyy-MM-dd HH:mm", "yyyy-MM-dd");
		ymd= DateUtil.string2DateStringForChinese(ymd);
		String hhmm = DateUtil.string2DateString(time, "yyyy-MM-dd HH:mm", "HH:mm");
		return ymd+" "+hhmm;
	}
	
	/**
	 * 获取一个时间点与当前时间的时差
	 * 显示规则：
		1.不满1小时：XX分钟前更新
		2.超过1小时：XX小时XX分钟前更新
		3.超过1天：XX天之前更新
		4.不满1分钟：刚刚更新
	 * @param begintimestr
	 * @return
	 * @throws ParseException
	 */
	public static String countTimesBeforeNow(Date begintimestr)
	{
		Date now =new Date();
		Date date=begintimestr;
		long l=now.getTime()-date.getTime();
		long day=l/(24*60*60*1000);
		long hour=(l/(60*60*1000)-day*24);
		long min=((l/(60*1000))-day*24*60-hour*60);
		long s=(l/1000-day*24*60*60-hour*60*60-min*60);
		String out = day+"天"+hour+"小时"+min+"分"+s+"秒";
		if(day>0){
			out = day+"天";
		}else if(hour>0){
			out = hour+"小时"+min+"分钟";
		}else if(min>0){
			out = min+"分钟";
		}else{
			out = "刚刚";
		}
		return out;
	}
	
	
	  public static String getTimeShowString(long milliseconds, boolean abbreviate) {
	        String dataString = "";
	        String timeStringBy24 = "";

	        Date currentTime = new Date(milliseconds);
	        Date today = new Date();
	        Calendar todayStart = Calendar.getInstance();
	        todayStart.set(Calendar.HOUR_OF_DAY, 0);
	        todayStart.set(Calendar.MINUTE, 0);
	        todayStart.set(Calendar.SECOND, 0);
	        todayStart.set(Calendar.MILLISECOND, 0);
	        Date todaybegin = todayStart.getTime();
	        Date yesterdaybegin = new Date(todaybegin.getTime() - 3600 * 24 * 1000);
	        Date preyesterday = new Date(yesterdaybegin.getTime() - 3600 * 24 * 1000);

	        if (!currentTime.before(todaybegin)) {
	            dataString = "今天";
	        } else if (!currentTime.before(yesterdaybegin)) {
	            dataString = "昨天";
	        } else if (!currentTime.before(preyesterday)) {
	            dataString = "前天";
	        } else if (isSameWeekDates(currentTime, today)) {
	            dataString = getWeekOfDate(currentTime);
	        } else {
	            SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
	            dataString = dateformatter.format(currentTime);
	        }

	        SimpleDateFormat timeformatter24 = new SimpleDateFormat("HH:mm", Locale.getDefault());
	        timeStringBy24 = timeformatter24.format(currentTime);

	        if (abbreviate) {
	            if (!currentTime.before(todaybegin)) {
	                return getTodayTimeBucket(currentTime);
	            } else {
	                return dataString;
	            }
	        } else {
	            return dataString + " " + timeStringBy24;
	        }
	    }

	  /**
	     * 根据不同时间段，显示不同时间
	     *
	     * @param date
	     * @return
	     */
	    public static String getTodayTimeBucket(Date date) {
	        Calendar calendar = Calendar.getInstance();
	        calendar.setTime(date);
	        SimpleDateFormat timeformatter0to11 = new SimpleDateFormat("KK:mm", Locale.getDefault());
	        SimpleDateFormat timeformatter1to12 = new SimpleDateFormat("hh:mm", Locale.getDefault());
	        int hour = calendar.get(Calendar.HOUR_OF_DAY);
	        if (hour >= 0 && hour < 5) {
	            return "凌晨 " + timeformatter0to11.format(date);
	        } else if (hour >= 5 && hour < 12) {
	            return "上午 " + timeformatter0to11.format(date);
	        } else if (hour >= 12 && hour < 18) {
	            return "下午 " + timeformatter1to12.format(date);
	        } else if (hour >= 18 && hour < 24) {
	            return "晚上 " + timeformatter1to12.format(date);
	        }
	        return "";
	    }
	    
	    /**
	     * 根据日期获得星期
	     *
	     * @param date
	     * @return
	     */
	    public static String getWeekOfDate(Date date) {
	        String[] weekDaysName = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
	        // String[] weekDaysCode = { "0", "1", "2", "3", "4", "5", "6" };
	        Calendar calendar = Calendar.getInstance();
	        calendar.setTime(date);
	        int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
	        return weekDaysName[intWeek];
	    }
	    
	    /**
	     * 判断两个日期是否在同一周
	     *
	     * @param date1
	     * @param date2
	     * @return
	     */
	    public static boolean isSameWeekDates(Date date1, Date date2) {
//	        Calendar cal1 = Calendar.getInstance();
//	        Calendar cal2 = Calendar.getInstance();
//	        cal1.setTime(date1);
//	        cal2.setTime(date2);
//	        int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
//	        if (0 == subYear) {
//	            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
//	                return true;
//	        } else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
//	            // 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
//	            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
//	                return true;
//	        } else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
//	            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
//	                return true;
//	        }
	        return false;
	    }
	    
	    
	    
 }